package course;

/**
 * @author zouran
 * createDate：2024/6/30  21:06
 */

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器端
 */
public class TCPFileUpload_Server {
    public static void main(String[] args) throws Exception {
        //思路
        //在本机 的8888端口监听, 等待连接
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务器端，监听8888端口，等待连接");
        //当没有客户端连接8888端口时，程序会 阻塞, 等待连接
        //如果有客户端连接，则会返回Socket对象，程序继续
        Socket socket = serverSocket.accept();

        //通过socket.getInputStream() 读取客户端写入到数据通道的数据, 并转换成字节数组
        BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream);
        //写入指定路径
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("D:\\Users\\13055\\Desktop\\bird.png"));
        bufferedOutputStream.write(bytes);
        //关闭IO流
        bufferedOutputStream.close();

        //向客户端回复收到图片
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bufferedWriter.write("收到图片!");
        bufferedWriter.flush();
        socket.shutdownOutput();


        //关闭所有流
        bufferedWriter.close();
        bufferedInputStream.close();
        socket.close();
        serverSocket.close();

    }
}